// ------------------------------------------------------------------------------------------
// Licensed by Interprise Solutions.
// http://www.InterpriseSolutions.com
// For details on this license please visit  the product homepage at the URL above.
// THE ABOVE NOTICE MUST REMAIN INTACT.
// ------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using InterpriseSuiteEcommerceControls;
using InterpriseSuiteEcommerceCommon;
using InterpriseSuiteEcommerceCommon.InterpriseIntegration;
using InterpriseSuiteEcommerceCommon.DTO;
using System.Linq;
using InterpriseSuiteEcommerceGateways;

namespace InterpriseSuiteEcommerce
{
    public partial class checkout1 : SkinBase
    {
        #region Variable Declaration

        private InterpriseShoppingCart _cart = null;
        private bool _weShouldRequirePayment = true;
        private bool _cartHasCouponAndIncludesFreeShipping = false;

        #endregion

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            SetCacheability();
            RequireSecurePage();
            RequireCustomerRecord();

            InitializeShoppingCart();
            PerformPageAccessLogic();
            InitializeAddressControls();
            InitializeShippingMethodControl();
            DisplayErrorMessageIfAny();
            InitializePaymentTermControl();
            CheckIfShouldRequireOver13BillingOption();
            ApplyStyles();
            DisplayOrderSummary();
        }

        private void DisplayOrderSummary()
        {
            OrderSummary.Text = _cart.RenderHTMLLiteral(new OnePageCheckOutLiteralRenderer());
        }

        private void ApplySignInOptionIfNotRegistered()
        {
            litSignin.Text = "<p align=\"left\">" +
                        AppLogic.GetString("createaccount.aspx.2", SkinID, ThisCustomer.LocaleSetting) +
                        " <a href=\"signin.aspx?checkout=" + true.ToString().ToLowerInvariant() + "&returnURL=" +
                        Server.UrlEncode("checkout1.aspx") + "\"><b>" +
                        AppLogic.GetString("createaccount.aspx.3", SkinID, ThisCustomer.LocaleSetting) + "</b></a>.</p>";
        }

        private void CheckIfShouldShowAddressSelectors()
        {
        }

        private void SetCacheability()
        {
            Response.CacheControl = "private";
            Response.Expires = 0;
            Response.AddHeader("pragma", "no-cache");
        }

        private void PerformPageAccessLogic()
        {
            // -----------------------------------------------------------------------------------------------
            // NOTE ON PAGE LOAD LOGIC:
            // We are checking here for required elements to allowing the customer to stay on this page.
            // Many of these checks may be redundant, and they DO add a bit of overhead in terms of db calls, but ANYTHING really
            // could have changed since the customer was on the last page. Remember, the web is completely stateless. Assume this
            // page was executed by ANYONE at ANYTIME (even someone trying to break the cart). 
            // It could have been yesterday, or 1 second ago, and other customers could have purchased limitied inventory products, 
            // coupons may no longer be valid, etc, etc, etc...
            // -----------------------------------------------------------------------------------------------

            if (ThisCustomer.IsCreditOnHold)
            {
                Response.Redirect("shoppingcart.aspx");
            }

            if (AppLogic.AppConfigBool("RequireOver13Checked") &&
                ThisCustomer.IsRegistered &&
                !ThisCustomer.IsOver13)
            {
                Response.Redirect("shoppingcart.aspx?errormsg=" + Server.UrlEncode(AppLogic.GetString("checkout.over13required", ThisCustomer.SkinID, ThisCustomer.LocaleSetting)));
            }

            if (ThisCustomer.IsNotRegistered)
            {
                if (AppLogic.AppConfigBool("PasswordIsOptionalDuringCheckout") == true)
                {
                    ApplySignInOptionIfNotRegistered();
                }
                else
                {
                    SetupForAnonRegistration();
                }
            }

            //If current user came from IS, chances are it has no Primary Billing Info! then tried to checkout
            if (ThisCustomer.IsRegistered && ThisCustomer.PrimaryBillingAddressID == String.Empty)
            {
                Response.Redirect("selectaddress.aspx?add=true&setPrimary=true&checkout=False&addressType=Billing&returnURL=account.aspx");
            }

            SectionTitle = AppLogic.GetString("checkout1.aspx.1", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);

            if (_cart.IsEmpty())
            {
                Response.Redirect("shoppingcart.aspx?resetlinkback=1");
            }

            if (_cart.InventoryTrimmed)
            {
                Response.Redirect("shoppingcart.aspx?resetlinkback=1&errormsg=" + Server.UrlEncode(AppLogic.GetString("shoppingcart.aspx.1", SkinID, ThisCustomer.LocaleSetting)));
            }

            string couponCode = string.Empty;
            string couponErrorMessage = string.Empty;
            if (_cart.HasCoupon(ref couponCode) && !_cart.IsCouponValid(ThisCustomer, couponCode, ref couponErrorMessage))
            {
                Response.Redirect("shoppingcart.aspx?resetlinkback=1&discountvalid=false");
            }

            if (!_cart.MeetsMinimumOrderAmount(AppLogic.AppConfigUSDecimal("CartMinOrderAmount")))
            {
                Response.Redirect("shoppingcart.aspx?resetlinkback=1");
            }

            if (!_cart.MeetsMinimumOrderQuantity(AppLogic.AppConfigUSInt("MinCartItemsBeforeCheckout")))
            {
                Response.Redirect("shoppingcart.aspx?resetlinkback=1");
            }

            if (!_cart.IsNoShippingRequired() && (_cart.HasMultipleShippingAddresses()) && _cart.NumItems() <= AppLogic.MultiShipMaxNumItemsAllowed() && _cart.CartAllowsShippingMethodSelection && _cart.NumItems() > 1)
            {
                Response.Redirect("checkoutshippingmult.aspx");
            }
        }

        private void SetupForAnonRegistration()
        {
            ctrlBillingAddress.RequirePassword = true;
            ctrlBillingAddress.ShowFirstName = true;
            ctrlBillingAddress.ShowLastName = true;
            ctrlBillingAddress.ShowAccountName = true;

            ctrlBillingAddress.RequireNoDuplicateCustomerEmail = true;
            ctrlBillingAddress.EvaluateNoDuplicateCustomerEmail += new System.ComponentModel.CancelEventHandler(ctrlBillingAddress_EvaluateNoDuplicateCustomerEmail);
        }

        private void ctrlBillingAddress_EvaluateNoDuplicateCustomerEmail(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = !Customer.IsEmailAlreadyInUse(ctrlBillingAddress.Email);
        }

        #region CheckWhichCountriesWeDontRequirePostalCodes

        private void CheckWhichCountriesWeDontRequirePostalCodes()
        {
            string postalCodeNotRequiredCountries = AppLogic.AppConfig("PostalCodeNotRequiredCountries");
            var countriesThatDontRequirePostalCodes = postalCodeNotRequiredCountries.Split(',').ToList();

            countriesThatDontRequirePostalCodes.ForEach(country =>
            {
                ctrlBillingAddress.PostalCodeOptionalCountryCodes.Add(country.Trim());
                ctrlShippingAddress.PostalCodeOptionalCountryCodes.Add(country.Trim());
            });
        }

        #endregion

        private void DisplayErrorMessageIfAny()
        {
            string errorMessage = CommonLogic.QueryStringCanBeDangerousContent("ErrorMsg", true);
            DisplayErrorMessageIfAny(errorMessage);
        }

        private void DisplayErrorMessageIfAny(string errorMessage)
        {
            if (CommonLogic.IsStringNullOrEmpty(errorMessage)) return;

            if (errorMessage.IndexOf("<script>", StringComparison.InvariantCultureIgnoreCase) != -1)
            {
                throw new ArgumentException("SECURITY EXCEPTION");
            }

            if (errorMessage == AppLogic.ro_INTERPRISE_GATEWAY_AUTHORIZATION_FAILED)
            {
                if (AppLogic.AppConfigBool("ShowGatewayError"))
                {
                    errorMessage = ThisCustomer.ThisCustomerSession["LastGatewayErrorMessage"];
                }
                else
                {
                    errorMessage = AppLogic.GetString("checkoutpayment.aspx.cs.1", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
                }
            }

            errorSummary.DisplayErrorMessage(errorMessage);
        }

        private void InitializeShoppingCart()
        {
            _cart = new InterpriseShoppingCart(base.EntityHelpers, ThisCustomer.SkinID, ThisCustomer, CartTypeEnum.ShoppingCart, string.Empty, false, true);
            bool computeVat = AppLogic.AppConfigBool("Vat.Enabled");
            _cart.BuildSalesOrderDetails();
            _cartHasCouponAndIncludesFreeShipping = _cart.CouponIncludesFreeShipping();
        }

        private void InitializeShippingMethodControl()
        {
            if (AppLogic.AppConfigBool("SkipShippingOnCheckout") ||
                !_cart.HasShippableComponents())
            {
                ctrlShippingMethod.SkipShipping = true;
                pnlShippingMethod.Visible = false;
            }
            else
            {
                if (_cartHasCouponAndIncludesFreeShipping)
                {
                    ctrlShippingMethod.Visible = false;
                }
                else
                {
                    InitializeShippingMethodControlValues();
                    AssignShippingMethodErrorSummary();
                    AssignShippingMethodValidationPrerequisites();
                    ChooseCommandTypeForRefreshShipping();

                    ctrlShippingMethod.LoadingImageUrl = string.Format("~/skins/Skin_{0}/images/loadingshipping.gif", ThisCustomer.SkinID);
                }

                InitializeShippingMethodCaptions();
            }
        }

        private void CheckIfShouldRequireOver13BillingOption()
        {
            ctrlBillingAddress.RequireOver13 = ThisCustomer.IsNotRegistered && AppLogic.AppConfigBool("RequireOver13Checked");
        }

        private void ChooseCommandTypeForRefreshShipping()
        {
            switch (AppLogic.AppConfig("ShippingMethodCommandType").ToLowerInvariant())
            {
                case "link":
                    ctrlShippingMethod.RefreshCommandType = ShippingMethodControl.RefreshCommandTypes.Link;
                    break;

                case "button":
                    ctrlShippingMethod.RefreshCommandType = ShippingMethodControl.RefreshCommandTypes.Button;
                    break;
            }

        }

        private void InitializeShippingMethodCaptions()
        {
            if (!_cart.CartAllowsShippingMethodSelection) return;

            if (_cartHasCouponAndIncludesFreeShipping)
            {
                lblSelectShippingMethod.Text = AppLogic.GetString("checkoutshipping.aspx.5", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            }
            else
            {
                if (Shipping.MultiShipEnabled() && _cart.TotalQuantity() > 1)
                {
                    lblSelectShippingMethod.Text = string.Format(AppLogic.GetString("checkoutshipping.aspx.7", SkinID, ThisCustomer.LocaleSetting), "checkoutshippingmult.aspx");
                }
                else
                {
                    lblSelectShippingMethod.Text = AppLogic.GetString("checkout1.aspx.4", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
                }

                lblRefreshShippingMethod.Text = AppLogic.GetString("checkout1.aspx.6", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
                ctrlShippingMethod.RefreshCommandCaption = AppLogic.GetString("checkout1.aspx.7", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            }
        }

        private void InitializeShippingMethodControlValues()
        {
            if (ThisCustomer.IsRegistered)
            {
                ctrlShippingMethod.ShippingAddress = ThisCustomer.PrimaryShippingAddress;
            }
        }

        private void AssignShippingMethodErrorSummary()
        {
            ctrlShippingMethod.ErrorSummaryControl = this.errorSummary;
        }

        private void AssignShippingMethodValidationPrerequisites()
        {
            ctrlShippingMethod.ShippingMethodRequiredErrorMessage = AppLogic.GetString("checkout1.aspx.9", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
        }

        private void InitializePaymentTermControl()
        {
            string baseTermOnThisCustomer = ThisCustomer.CustomerCode;

            if (ThisCustomer.IsNotRegistered)
            {
                baseTermOnThisCustomer = ThisCustomer.AnonymousCustomerCode;
            }

            ctrlPaymentTerm.PaymentTermOptions = PaymentTermDTO.GetAllForGroup(baseTermOnThisCustomer, ThisCustomer.PrimaryShippingAddress); //availableTerms;
            ctrlPaymentTerm.CaptionWidth = Unit.Percentage(30);
            ctrlPaymentTerm.InputWidth = Unit.Percentage(70);
            ctrlPaymentTerm.ShowCardStarDate = AppLogic.AppConfigBool("ShowCardStartDateFields");

            AssignPaymentTermDatasources();
            InitializePaymentTermControlValues();
            AssignPaymentTermCaptions();
            AssignPaymentTermErrorSummary();
            AssignPaymentTermValidationPrerequisites();
            CheckIfWeShouldRequirePayment();
            InitializeTermsAndConditions();

            lblSelectPaymentTerm.Text = AppLogic.GetString("checkout1.aspx.5", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
        }

        private void InitializeTermsAndConditions()
        {
            if (AppLogic.AppConfigBool("RequireTermsAndConditionsAtCheckout"))
            {
                ctrlPaymentTerm.RequireTermsAndConditions = true;
                ctrlPaymentTerm.RequireTermsAndConditionsPrompt = AppLogic.GetString("checkoutpayment.aspx.5", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);

                Topic t = new Topic("checkouttermsandconditions", ThisCustomer.LocaleSetting, ThisCustomer.SkinID);
                ctrlPaymentTerm.TermsAndConditionsHTML = t.Contents;
            }
            else
            {
                ctrlPaymentTerm.RequireTermsAndConditions = false;
            }
        }

        private void InitializePaymentTermControlValues()
        {
            ctrlPaymentTerm.NameOnCard = ThisCustomer.PrimaryBillingAddress.CardName;
            ctrlPaymentTerm.CardExpiryMonth = ThisCustomer.PrimaryBillingAddress.CardExpirationMonth;
            ctrlPaymentTerm.CardExpiryYear = ThisCustomer.PrimaryBillingAddress.CardExpirationYear;
            ctrlPaymentTerm.CardType = ThisCustomer.PrimaryBillingAddress.CardType;
            ctrlPaymentTerm.CardStartMonth = ThisCustomer.PrimaryBillingAddress.CardStartMonth;
            ctrlPaymentTerm.CardStartYear = ThisCustomer.PrimaryBillingAddress.CardStartYear;
        }

        private void AssignPaymentTermDatasources()
        {
            var cardTypes = new List<string>();
            cardTypes.Add(AppLogic.GetString("address.cs.5", ThisCustomer.SkinID, ThisCustomer.LocaleSetting));

            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (var reader = DB.GetRSFormat(con, "SELECT CreditCardType FROM CustomerCreditCardType with (NOLOCK) WHERE IsActive = 1"))
                {
                    while (reader.Read())
                    {
                        cardTypes.Add(DB.RSField(reader, "CreditCardType"));
                    }
                }
            }

            ctrlPaymentTerm.CardTypeDataSource = cardTypes;

            int currentYear = DateTime.Now.Year;
            var startYears = new List<string>();
            var expirationYears = new List<string>();

            startYears.Add(AppLogic.GetString("address.cs.8", ThisCustomer.SkinID, ThisCustomer.LocaleSetting));
            expirationYears.Add(AppLogic.GetString("address.cs.8", ThisCustomer.SkinID, ThisCustomer.LocaleSetting));
            for (int offsetYear = 0; offsetYear <= 10; offsetYear++)
            {
                startYears.Add((currentYear - offsetYear).ToString());
                expirationYears.Add((currentYear + offsetYear).ToString());
            }

            ctrlPaymentTerm.StartYearDataSource = startYears;
            ctrlPaymentTerm.ExpiryYearDataSource = expirationYears;

            var months = new List<string>();
            months.Add(AppLogic.GetString("address.cs.7", ThisCustomer.SkinID, ThisCustomer.LocaleSetting));
            for (int month = 1; month <= 12; month++)
            {
                months.Add(month.ToString().PadLeft(2, '0'));
            }
            ctrlPaymentTerm.StartMonthDataSource = months;
            ctrlPaymentTerm.ExpiryMonthDataSource = months;
        }

        private void AssignPaymentTermValidationPrerequisites()
        {
            ctrlPaymentTerm.PaymentTermRequiredErrorMessage = AppLogic.GetString("checkout1.aspx.10", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlPaymentTerm.NameOnCardRequiredErrorMessage = AppLogic.GetString("checkout1.aspx.11", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlPaymentTerm.CardNumberRequiredErrorMessage = AppLogic.GetString("checkout1.aspx.12", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlPaymentTerm.CVVRequiredErrorMessage = AppLogic.GetString("checkout1.aspx.13", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlPaymentTerm.CardTypeInvalidErrorMessage = AppLogic.GetString("checkout1.aspx.14", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlPaymentTerm.ExpirationMonthInvalidErrorMessage = AppLogic.GetString("checkout1.aspx.15", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlPaymentTerm.ExpirationYearInvalidErrorMessage = AppLogic.GetString("checkout1.aspx.16", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlPaymentTerm.StartMonthInvalidErrorMessage = AppLogic.GetString("checkout1.aspx.25", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlPaymentTerm.StartYearInvalidErrorMessage = AppLogic.GetString("checkout1.aspx.26", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlPaymentTerm.UnknownCardTypeErrorMessage = AppLogic.GetString("checkout1.aspx.17", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlPaymentTerm.NoCardNumberProvidedErrorMessage = AppLogic.GetString("checkout1.aspx.18", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlPaymentTerm.CardNumberInvalidFormatErrorMessage = AppLogic.GetString("checkout1.aspx.19", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlPaymentTerm.CardNumberInvalidErrorMessage = AppLogic.GetString("checkout1.aspx.20", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlPaymentTerm.CardNumberInAppropriateNumberOfDigitsErrorMessage = AppLogic.GetString("checkout1.aspx.21", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
        }

        private void AssignPaymentTermErrorSummary()
        {
            ctrlPaymentTerm.ErrorSummaryControl = this.errorSummary;
        }

        private void InitializeAddressControls()
        {
            LoadAllAvailableCountriesAndAssignRegistriesForAddresses();
            LoadAvailableSalutationsForBillingAddress();
            CheckWhichCountriesWeDontRequirePostalCodes();
            AssignAddressCaptions();
            AssignAddressValidationPrerequisites();
            RequireFieldsForNotRegisteredCustomers();
            LoadDefaultAddresses();
            InitializeAddressSelectors();
            SetCopyBillingInfoScript();
            AssignAddressErrorSummary();
            ctrlBillingAddress.ShowCounty = AppLogic.AppConfigBool("Address.ShowCounty");
            ctrlShippingAddress.ShowCounty = AppLogic.AppConfigBool("Address.ShowCounty");
        }

        private void RequireFieldsForNotRegisteredCustomers()
        {
            ctrlBillingAddress.RequireEmail = ThisCustomer.IsNotRegistered;
            ctrlBillingAddress.RequireOver13 = ThisCustomer.IsNotRegistered;
        }

        private void AssignAddressErrorSummary()
        {
            ctrlBillingAddress.ErrorSummaryControl = this.errorSummary;
            ctrlShippingAddress.ErrorSummaryControl = this.errorSummary;
        }

        private void SetCopyBillingInfoScript()
        {
            chkSameAsBilling.Attributes.Add(
                "onclick",
                string.Format(
                    "if(this.checked){{ ise.Controls.AddressController.getControl('{0}').setValue(ise.Controls.AddressController.getControl('{1}').getValue()); ise.Controls.AddressController.getControl('{0}').setDisabled(true);}}else{{ise.Controls.AddressController.getControl('{0}').setDisabled(false); ise.Pages.OnePageCheckOut.shippingAddressSelectorControl.setSelectedIndex(0, true);}} ise.Pages.OnePageCheckOut.shippingMethodControl.onRefreshClicked();",
                    ctrlShippingAddress.ClientID,
                    ctrlBillingAddress.ClientID
                )
            );
        }

        private void InitializeAddressSelectors()
        {
            if (ThisCustomer.IsRegistered)
            {
                ctrlBillingSelector.AddressesDataSource = ThisCustomer.BillingAddresses;
                ctrlBillingSelector.DisplayLength = 100;

                pnlSelectBillingAddress.Visible = ThisCustomer.BillingAddresses.Count > 1;

                //Get the list of shipping addresses
                var shippingAddresses = ThisCustomer.ShippingAddresses;

                //Add a blank item at the top of the list.
                var defaultAddress = new Address()
                {
                    AddressID = "DEFAULT",
                    AddressType = AddressTypes.Shipping,
                    ResidenceType = ResidenceTypes.Residential,

                };

                //Set the ID to DEFAULT. We will be keying off of this in the javascript when it's selected.
                shippingAddresses.Insert(0, defaultAddress);

                ctrlShippingSelector.AddressesDataSource = shippingAddresses;
                ctrlShippingSelector.DisplayLength = 100;
                pnlSelectShippingAddress.Visible = ThisCustomer.ShippingAddresses.Count > 1;
            }
            else
            {
                pnlSelectBillingAddress.Visible = false;
                pnlSelectShippingAddress.Visible = false;
            }
        }

        private void HideAddressSelectors()
        {
            pnlSelectBillingAddress.Visible = false;
            pnlSelectShippingAddress.Visible = false;
        }

        private void LoadDefaultAddresses()
        {
            var defaultBillingAddress = ThisCustomer.PrimaryBillingAddress;

            ctrlBillingAddress.Salutation = ThisCustomer.Salutation;
            ctrlBillingAddress.FirstName = ThisCustomer.FirstName;
            ctrlBillingAddress.LastName = ThisCustomer.LastName;
            ctrlBillingAddress.AccountName = defaultBillingAddress.Name;
            ctrlBillingAddress.Email = defaultBillingAddress.EMail;
            ctrlBillingAddress.PhoneNumber = defaultBillingAddress.Phone;
            ctrlBillingAddress.AccountName = defaultBillingAddress.Name;
            ctrlBillingAddress.CountryCode = defaultBillingAddress.Country;
            ctrlBillingAddress.ResidenceType = defaultBillingAddress.ResidenceType;
            ctrlBillingAddress.Address = defaultBillingAddress.Address1;
            ctrlBillingAddress.City = defaultBillingAddress.City;
            ctrlBillingAddress.State = defaultBillingAddress.State;
            ctrlBillingAddress.County = defaultBillingAddress.County;
            ctrlBillingAddress.PostalCode = defaultBillingAddress.PostalCode;
            ctrlBillingAddress.Over13Checked = ThisCustomer.IsOver13;

            var defaultShippingAddress = ThisCustomer.PrimaryShippingAddress;
            ctrlShippingAddress.PhoneNumber = defaultShippingAddress.Phone;
            ctrlShippingAddress.AccountName = defaultShippingAddress.Name;
            ctrlShippingAddress.CountryCode = defaultShippingAddress.Country;
            ctrlShippingAddress.ResidenceType = defaultShippingAddress.ResidenceType;
            ctrlShippingAddress.Address = defaultShippingAddress.Address1;
            ctrlShippingAddress.City = defaultShippingAddress.City;
            ctrlShippingAddress.State = defaultShippingAddress.State;
            ctrlShippingAddress.County = defaultShippingAddress.County;
            ctrlShippingAddress.PostalCode = defaultShippingAddress.PostalCode;
        }

        private void ApplyStyles()
        {
            imgAccountInfo.ImageUrl = CommonLogic.IIF((ThisCustomer.IsNotRegistered),
                                                        AppLogic.LocateImageURL("skins/Skin_" + SkinID.ToString() + "/images/1_billinginfo.gif"),
                                                        AppLogic.LocateImageURL("skins/Skin_" + SkinID.ToString() + "/images/1_accountandbillinginfo.gif"));

            tblAccountInfo.Attributes["style"] = AppLogic.AppConfig("BoxFrameStyle");

            imgShippingInfo.ImageUrl = AppLogic.LocateImageURL("skins/Skin_" + SkinID.ToString() + "/images/2_shippinginfo.gif");
            tblShippingInfo.Attributes["style"] = AppLogic.AppConfig("BoxFrameStyle");

            imgShippingMethod.ImageUrl = AppLogic.LocateImageURL("skins/Skin_" + SkinID.ToString() + "/images/3_shippingMethod.gif");
            tblShippingMethod.Attributes["style"] = AppLogic.AppConfig("BoxFrameStyle");

            imgPaymentTerm.ImageUrl = AppLogic.LocateImageURL("skins/Skin_" + SkinID.ToString() + "/images/4_paymentTerm.gif");
            tblPaymentTerm.Attributes["style"] = AppLogic.AppConfig("BoxFrameStyle");

            btnCompletePurchase.Text = AppLogic.GetString("checkoutreview.aspx.7", SkinID, ThisCustomer.LocaleSetting);
        }

        private void LoadAllAvailableCountriesAndAssignRegistriesForAddresses()
        {
            var countries = CountryAddressDTO.GetAllCountries();

            ctrlBillingAddress.Countries = countries;
            ctrlBillingAddress.RegisterCountries = true;

            ctrlShippingAddress.Countries = countries;
            ctrlShippingAddress.RegisterCountries = false;
        }

        private void AssignAddressCaptions()
        {
            AssignBillingAddressCaptions();
            AssignShippingAddressCaptions();
        }

        private void AssignAddressValidationPrerequisites()
        {
            AssignBillingAddressValidatorPrerequisites();
            AssignShippingAddressValidatorPrerequisites();
        }

        private void LoadAvailableSalutationsForBillingAddress()
        {
            var salutations = new List<KeyValuePair<string, string>>();
            salutations.Add(new KeyValuePair<string, string>("Select One", string.Empty));

            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (var reader = DB.GetRSFormat(con, "SELECT SalutationDescription FROM SystemSalutation with (NOLOCK) WHERE IsActive = 1"))
                {
                    while (reader.Read())
                    {
                        salutations.Add(new KeyValuePair<string, string>(DB.RSField(reader, "SalutationDescription"), DB.RSField(reader, "SalutationDescription")));
                    }
                }
            }
            ctrlBillingAddress.SetSalutations(salutations);
        }

        private void AssignBillingAddressCaptions()
        {
            if (ThisCustomer.IsNotRegistered)
            {
                if (AppLogic.AppConfigBool("PasswordIsOptionalDuringCheckout") == true)
                {
                    ctrlBillingAddress.AccountNameCaption = AppLogic.GetString("createaccount.aspx.34", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
                }
                else
                {
                    ctrlBillingAddress.AccountNameCaption = AppLogic.GetString("createaccount.aspx.36", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
                    ctrlBillingAddress.FirstNameCaption = AppLogic.GetString("createaccount.aspx.6", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
                    ctrlBillingAddress.LastNameCaption = AppLogic.GetString("createaccount.aspx.7", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
                    ctrlBillingAddress.RequireNoDuplicateCustomerEmailErrorMessage = AppLogic.GetString("createaccount.aspx.94", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
                }
            }
            else
            {
                ctrlBillingAddress.AccountNameCaption = AppLogic.GetString("createaccount.aspx.36", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            }

            bool _postalCodeOptionalCountry = false;
            foreach (string country in ctrlBillingAddress.PostalCodeOptionalCountryCodes)
            {
                if (country == ctrlBillingAddress.CountryCode) { _postalCodeOptionalCountry = true; }
            }
            if (_postalCodeOptionalCountry)
            {
                ctrlBillingAddress.WithOutStatePostalCaption = AppLogic.GetString("createaccount.aspx.30", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
                ctrlBillingAddress.WithStateCityStatePostalCaption = AppLogic.GetString("createaccount.aspx.29", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            }
            else
            {
                ctrlBillingAddress.WithOutStatePostalCaption = AppLogic.GetString("createaccount.aspx.77", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
                ctrlBillingAddress.WithStateCityStatePostalCaption = AppLogic.GetString("createaccount.aspx.31", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            }

            lblSelectBillingAddress.Text = AppLogic.GetString("checkout1.aspx.2", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlBillingAddress.SalutationCaption = AppLogic.GetString("createaccount.aspx.35", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlBillingAddress.EmailCaption = AppLogic.GetString("createaccount.aspx.8", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlBillingAddress.OkToEmailCaption = AppLogic.GetString("createaccount.aspx.11", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlBillingAddress.Over13YearsOldCaption = AppLogic.GetString("createaccount.aspx.26", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlBillingAddress.SubScriptionOptionCaption = AppLogic.GetString("createaccount.aspx.14", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlBillingAddress.AddressCaption = AppLogic.GetString("createaccount.aspx.17", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlBillingAddress.ResidenceTypeCaption = AppLogic.GetString("address.cs.15", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlBillingAddress.BusinessTypeCaption = AppLogic.GetString("address.cs.18", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlBillingAddress.TaxNumberCaption = AppLogic.GetString("address.cs.17", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlBillingAddress.CountryCaption = AppLogic.GetString("createaccount.aspx.18", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlBillingAddress.FirstNameCaption = AppLogic.GetString("createaccount.aspx.6", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlBillingAddress.LastNameCaption = AppLogic.GetString("createaccount.aspx.7", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlBillingAddress.PhoneNumberCaption = AppLogic.GetString("createaccount.aspx.16", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlBillingAddress.WithOutStateCityCaption = AppLogic.GetString("createaccount.aspx.33", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlBillingAddress.CountyCaption = AppLogic.GetString("createaccount.aspx.32", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlBillingAddress.PasswordCaption = AppLogic.GetString("createaccount.aspx.9", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlBillingAddress.PasswordMinLengthCaption = AppLogic.GetString("createaccount.aspx.4", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlBillingAddress.ConfirmPasswordCaption = AppLogic.GetString("createaccount.aspx.10", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlBillingAddress.CaptchaCaption = AppLogic.GetString("signin.aspx.18", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlBillingAddress.OkToEmailYesOptionCaption = AppLogic.GetString("createaccount.aspx.12", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlBillingAddress.OkToEmailNoOptionCaption = AppLogic.GetString("createaccount.aspx.13", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
        }

        private void AssignShippingAddressCaptions()
        {
            bool _postalCodeOptionalCountry = false;
            ctrlShippingAddress.PostalCodeOptionalCountryCodes.ForEach(country =>
            {
                if (country == ctrlShippingAddress.CountryCode) { _postalCodeOptionalCountry = true; }
            });

            if (_postalCodeOptionalCountry)
            {
                ctrlShippingAddress.WithOutStatePostalCaption = AppLogic.GetString("createaccount.aspx.30", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
                ctrlShippingAddress.WithStateCityStatePostalCaption = AppLogic.GetString("createaccount.aspx.29", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            }
            else
            {
                ctrlShippingAddress.WithOutStatePostalCaption = AppLogic.GetString("createaccount.aspx.77", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
                ctrlShippingAddress.WithStateCityStatePostalCaption = AppLogic.GetString("createaccount.aspx.31", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            }

            lblSelectShippingAddress.Text = AppLogic.GetString("checkout1.aspx.3", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlShippingAddress.AccountNameCaption = AppLogic.GetString("createaccount.aspx.34", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlShippingAddress.AddressCaption = AppLogic.GetString("createaccount.aspx.22", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlShippingAddress.ResidenceTypeCaption = AppLogic.GetString("address.cs.15", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlShippingAddress.CountryCaption = AppLogic.GetString("createaccount.aspx.23", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlShippingAddress.PhoneNumberCaption = AppLogic.GetString("createaccount.aspx.16", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlShippingAddress.WithOutStateCityCaption = AppLogic.GetString("createaccount.aspx.33", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlShippingAddress.CountyCaption = AppLogic.GetString("createaccount.aspx.32", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
        }

        private void AssignBillingAddressValidatorPrerequisites()
        {
            ctrlBillingAddress.FirstNameRequiredErrorMessage = AppLogic.GetString("createaccount.aspx.37", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlBillingAddress.LastNameRequiredErrorMessage = AppLogic.GetString("createaccount.aspx.38", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlBillingAddress.AccountNameRequiredErrorMessage = AppLogic.GetString("createaccount.aspx.39", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlBillingAddress.AddressRequiredErrorMessage = AppLogic.GetString("createaccount.aspx.40", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlBillingAddress.PhoneRequiredErrorMessage = AppLogic.GetString("createaccount.aspx.41", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);

            ctrlBillingAddress.FirstNameMaximumCharacterLength = 50;
            ctrlBillingAddress.FirstNameMaximumCharacterLengthErrorMessage = AppLogic.GetString("createaccount.aspx.42", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlBillingAddress.LastNameMaximumCharacterLength = 50;
            ctrlBillingAddress.LastNameMaximumCharacterLengthErrorMessage = AppLogic.GetString("createaccount.aspx.43", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlBillingAddress.AccountNameMaximumCharacterLength = 100;
            ctrlBillingAddress.AccountNameMaximumCharacterLengthErrorMessage = AppLogic.GetString("createaccount.aspx.44", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlBillingAddress.AddressMaximumCharacterLength = 200;
            ctrlBillingAddress.AddressMaximumCharacterLengthErrorMessage = AppLogic.GetString("createaccount.aspx.45", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlBillingAddress.PhoneMaximumCharacterLength = 50;
            ctrlBillingAddress.PhoneMaximumCharacterLengthErrorMessage = AppLogic.GetString("createaccount.aspx.46", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);

            ctrlBillingAddress.EmailRequiredErrorMessage = AppLogic.GetString("createaccount.aspx.47", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlBillingAddress.PasswordRequiredErrorMessage = AppLogic.GetString("createaccount.aspx.48", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlBillingAddress.ConfirmPasswordRequiredErrorMessage = AppLogic.GetString("createaccount.aspx.49", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);

            ctrlBillingAddress.EmailMaximumCharacterLength = 50;
            ctrlBillingAddress.EmailMaximumCharacterLengthErrorMessage = AppLogic.GetString("createaccount.aspx.50", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlBillingAddress.PasswordMinimumCharacterLength = 4;
            ctrlBillingAddress.PasswordMaximumCharacterLength = 50;
            ctrlBillingAddress.PasswordMaximumCharacterLengthErrorMessage = AppLogic.GetString("createaccount.aspx.51", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlBillingAddress.CompareConfirmPasswordErrorMessage = AppLogic.GetString("createaccount.aspx.52", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlBillingAddress.EmailValidationRegularExpression = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
            ctrlBillingAddress.EmailValidationRegularExpressionErrorMessage = AppLogic.GetString("createaccount.aspx.53", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);

            ctrlBillingAddress.CityRequiredErrorMessage = AppLogic.GetString("createaccount.aspx.69", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlBillingAddress.CityMaximumCharacterLength = 50;
            ctrlBillingAddress.CityMaximumCharacterLengthErrorMessage = AppLogic.GetString("createaccount.aspx.73", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);

            ctrlBillingAddress.PostalCodeRequiredErrorMessage = AppLogic.GetString("createaccount.aspx.70", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlBillingAddress.PostalCodeMaximumCharacterLength = 10;
            ctrlBillingAddress.PostalCodeMaximumCharacterLengthErrorMessage = AppLogic.GetString("createaccount.aspx.74", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);

            ctrlBillingAddress.RequireNoDuplicateCustomerEmailErrorMessage = AppLogic.GetString("createaccount.aspx.94", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);

            ctrlBillingAddress.CaptchaRequiredErrorMessage = AppLogic.GetString("createaccount.aspx.54", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlBillingAddress.CaptchaInvalidErrorMessage = AppLogic.GetString("createaccount.aspx.55", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);

            ctrlBillingAddress.StrongPasswordValidationRegularExpression = AppLogic.AppConfig("CustomerPwdValidator");
            ctrlBillingAddress.StrongPasswordValidationErrorMessage = AppLogic.GetString("createaccount.aspx.28", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);

            ctrlBillingAddress.RequireBusinessTypeSelectErrorMessage = AppLogic.GetString("createaccount.aspx.78", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);

            ctrlBillingAddress.POBoxAddressNotAllowedErrorMessage = AppLogic.GetString("address.cs.19", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
        }

        private void AssignShippingAddressValidatorPrerequisites()
        {
            ctrlShippingAddress.FirstNameRequiredErrorMessage = AppLogic.GetString("createaccount.aspx.56", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlShippingAddress.LastNameRequiredErrorMessage = AppLogic.GetString("createaccount.aspx.57", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlShippingAddress.AccountNameRequiredErrorMessage = AppLogic.GetString("createaccount.aspx.58", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlShippingAddress.AddressRequiredErrorMessage = AppLogic.GetString("createaccount.aspx.59", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlShippingAddress.PhoneRequiredErrorMessage = AppLogic.GetString("createaccount.aspx.60", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);

            ctrlShippingAddress.FirstNameMaximumCharacterLength = 50;
            ctrlShippingAddress.FirstNameMaximumCharacterLengthErrorMessage = AppLogic.GetString("createaccount.aspx.61", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlShippingAddress.LastNameMaximumCharacterLength = 50;
            ctrlShippingAddress.LastNameMaximumCharacterLengthErrorMessage = AppLogic.GetString("createaccount.aspx.62", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlShippingAddress.AccountNameMaximumCharacterLength = 100;
            ctrlShippingAddress.AccountNameMaximumCharacterLengthErrorMessage = AppLogic.GetString("createaccount.aspx.63", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlShippingAddress.AddressMaximumCharacterLength = 200;
            ctrlShippingAddress.AddressMaximumCharacterLengthErrorMessage = AppLogic.GetString("createaccount.aspx.64", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlShippingAddress.PhoneMaximumCharacterLength = 50;
            ctrlShippingAddress.PhoneMaximumCharacterLengthErrorMessage = AppLogic.GetString("createaccount.aspx.65", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);

            ctrlShippingAddress.CityRequiredErrorMessage = AppLogic.GetString("createaccount.aspx.71", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlShippingAddress.CityMaximumCharacterLength = 50;
            ctrlShippingAddress.CityMaximumCharacterLengthErrorMessage = AppLogic.GetString("createaccount.aspx.75", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);

            ctrlShippingAddress.PostalCodeRequiredErrorMessage = AppLogic.GetString("createaccount.aspx.72", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlShippingAddress.PostalCodeMaximumCharacterLength = 10;
            ctrlShippingAddress.PostalCodeMaximumCharacterLengthErrorMessage = AppLogic.GetString("createaccount.aspx.76", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);

            ctrlShippingAddress.POBoxAddressNotAllowedErrorMessage = AppLogic.GetString("address.cs.20", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
        }

        private void AssignPaymentTermCaptions()
        {
            ctrlPaymentTerm.NameOnCardCaption = AppLogic.GetString("address.cs.1", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlPaymentTerm.CardNumberCaption = AppLogic.GetString("address.cs.2", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlPaymentTerm.CardTypeCaption = AppLogic.GetString("address.cs.4", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlPaymentTerm.CVVCaption = AppLogic.GetString("address.cs.3", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlPaymentTerm.WhatIsCVVCaption = AppLogic.GetString("address.cs.9", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlPaymentTerm.ExpirationDateCaption = AppLogic.GetString("address.cs.6", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlPaymentTerm.CardStartDateCaption = AppLogic.GetString("checkout1.aspx.22", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlPaymentTerm.CardIssueNumberCaption = AppLogic.GetString("checkout1.aspx.23", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlPaymentTerm.CardIssueNumberInfoCaption = AppLogic.GetString("checkout1.aspx.24", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlPaymentTerm.PONumberCaption = AppLogic.GetString("checkoutpo.aspx.1", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            ctrlPaymentTerm.NoPaymentRequiredCaption = AppLogic.GetString("checkoutpayment.aspx.8", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
        }

        private void CheckIfWeShouldRequirePayment()
        {
            if (_cart.GetOrderTotal() == System.Decimal.Zero &&
                AppLogic.AppConfigBool("SkipPaymentEntryOnZeroDollarCheckout"))
            {
                ctrlPaymentTerm.NoPaymentRequired = true;
                _weShouldRequirePayment = false;
                _cart.MakePaymentTermNotRequired();
            }
            else
            {
                ctrlPaymentTerm.NoPaymentRequired = false;
                _weShouldRequirePayment = true;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            var script = new StringBuilder();

            script.Append("<script type=\"text/javascript\" language=\"Javascript\" >\n");
            script.Append("$add_windowLoad(\n");
            script.Append(" function() { \n");

            script.AppendFormat("   ise.StringResource.registerString('{0}', '{1}');\n", "checkoutshipping.aspx.9", AppLogic.GetString("checkoutshipping.aspx.9", ThisCustomer.SkinID, ThisCustomer.LocaleSetting));
            script.AppendFormat("   ise.StringResource.registerString('{0}', '{1}');\n", "checkoutshipping.aspx.10", AppLogic.GetString("checkoutshipping.aspx.10", ThisCustomer.SkinID, ThisCustomer.LocaleSetting));
            script.AppendFormat("   ise.StringResource.registerString('{0}', '{1}');\n", "checkoutshipping.aspx.11", AppLogic.GetString("checkoutshipping.aspx.11", ThisCustomer.SkinID, ThisCustomer.LocaleSetting));
            script.AppendFormat("   ise.StringResource.registerString('{0}', '{1}');\n", "checkoutshipping.aspx.12", AppLogic.GetString("checkoutshipping.aspx.12", ThisCustomer.SkinID, ThisCustomer.LocaleSetting));

            script.AppendFormat("   ise.Pages.OnePageCheckOut.setBillingAddressControlId('{0}');\n", this.ctrlBillingAddress.ClientID);
            script.AppendFormat("   ise.Pages.OnePageCheckOut.setShippingAddressControlId('{0}');\n", this.ctrlShippingAddress.ClientID);
            script.AppendFormat("   ise.Pages.OnePageCheckOut.setBillingAddressSelectorControlId('{0}');\n", this.ctrlBillingSelector.ClientID);
            script.AppendFormat("   ise.Pages.OnePageCheckOut.setShippingAddressSelectorControlId('{0}');\n", this.ctrlShippingSelector.ClientID);

            script.AppendFormat("   ise.Pages.OnePageCheckOut.setControlEvents('{0}','{1}','{2}','{3}');\n", this.ctrlBillingAddress.ClientID, this.ctrlShippingAddress.ClientID, chkSameAsBilling.ClientID, this.ctrlShippingMethod.ClientID);

            bool shouldTogglePaymentTermBySelectedShippingMethod = _cart.GetOrderTotal() == System.Decimal.Zero &&
                                                                    AppLogic.AppConfigBool("SkipPaymentEntryOnZeroDollarCheckout");

            if (!_cartHasCouponAndIncludesFreeShipping)
            {
                script.AppendFormat("   ise.Pages.OnePageCheckOut.setShippingMethodControlId('{0}');\n", this.ctrlShippingMethod.ClientID);
            }
            script.AppendFormat("   ise.Pages.OnePageCheckOut.setPaymentTermControlId('{0}');\n", this.ctrlPaymentTerm.ClientID);
            script.AppendFormat("   ise.Pages.OnePageCheckOut.setForm('{0}');\n", this.frmOnePageCheckOut.ClientID);

            script.Append(" }\n");
            script.Append(");\n");
            script.Append("</script>\n");

            Page.ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), script.ToString());
        }

        protected override void RegisterScriptsAndServices(ScriptManager manager)
        {
            manager.Scripts.Add(new ScriptReference("~/jscripts/tooltip.js"));
            manager.Scripts.Add(new ScriptReference("~/jscripts/address_ajax.js"));
            manager.Scripts.Add(new ScriptReference("~/jscripts/shippingmethod_ajax.js"));
            manager.Scripts.Add(new ScriptReference("~/jscripts/creditcard.js"));
            manager.Scripts.Add(new ScriptReference("~/jscripts/paymentterm_ajax.js"));
            manager.Scripts.Add(new ScriptReference("~/jscripts/onepagecheckout_ajax.js"));

            var service = new ServiceReference("~/actionservice.asmx");
            service.InlineScript = false;
            manager.Services.Add(service);
        }

        private void UpdateAnonCustomerRecordIsOver13()
        {
            if (!AppLogic.AppConfigBool("RequireOver13Checked") && !ThisCustomer.IsNotRegistered) return;

            int isover13 = CommonLogic.IIF(ctrlBillingAddress.Over13Checked, 1, 0);
            int isupdated = 1;
            string updateAnonRecordIfIsover13 = string.Format("UPDATE EcommerceCustomer SET IsOver13 = {0} , IsUpdated = {1} WHERE CustomerID = {2}", DB.SQuote(isover13.ToString()), DB.SQuote(isupdated.ToString()), DB.SQuote(ThisCustomer.CustomerID.ToString()));
            DB.ExecuteSQL(updateAnonRecordIfIsover13);
        }

        protected void btnCompletePurchase_Click(object sender, EventArgs e)
        {
            if (!this.IsValid) return;

            if (AppLogic.AppConfigBool("RequireOver13Checked") &&
                ThisCustomer.IsNotRegistered &&
                !ctrlBillingAddress.Over13Checked)
            {
                errorSummary.DisplayErrorMessage(AppLogic.GetString("checkout.over13required", ThisCustomer.SkinID, ThisCustomer.LocaleSetting));
                return;
            }

            Address preferredBillingAddress = null;
            Address preferredShippingAddress = null;

            if (ThisCustomer.IsRegistered)
            {
                if (ThisCustomer.HasMoreThanOneBillingAddress)
                {
                    preferredBillingAddress = ctrlBillingSelector.SelectedAddress;
                }
                else
                {
                    preferredBillingAddress = ThisCustomer.PrimaryBillingAddress;
                }

                if (ThisCustomer.HasMoreThanOneShippingAddress)
                {
                    preferredShippingAddress = ctrlShippingSelector.SelectedAddress;
                }
                else
                {
                    preferredShippingAddress = ThisCustomer.PrimaryShippingAddress;
                }
            }
            else
            {
                // make new...
                preferredBillingAddress = Address.New(ThisCustomer, AddressTypes.Billing);
                preferredShippingAddress = Address.New(ThisCustomer, AddressTypes.Shipping);
            }

            ThisCustomer.Salutation = ctrlBillingAddress.Salutation;
            preferredBillingAddress.EMail = ctrlBillingAddress.Email;
            preferredBillingAddress.FirstName = ctrlBillingAddress.FirstName;
            preferredBillingAddress.LastName = ctrlBillingAddress.LastName;
            preferredBillingAddress.Company = ctrlBillingAddress.AccountName;
            preferredBillingAddress.Name = ctrlBillingAddress.AccountName;
            preferredBillingAddress.ResidenceType = ctrlBillingAddress.ResidenceType;
            preferredBillingAddress.Address1 = ctrlBillingAddress.Address;
            preferredBillingAddress.City = ctrlBillingAddress.City;
            preferredBillingAddress.State = ctrlBillingAddress.State;
            preferredBillingAddress.PostalCode = ctrlBillingAddress.PostalCode;
            preferredBillingAddress.County = ctrlBillingAddress.County;
            preferredBillingAddress.Country = ctrlBillingAddress.CountryCode;
            preferredBillingAddress.Phone = ctrlBillingAddress.PhoneNumber;
            if (AppLogic.AppConfigBool("PasswordIsOptionalDuringCheckout") == false &&
                ctrlBillingAddress.RequirePassword)
            {
                ThisCustomer.Password = ctrlBillingAddress.Password;
                ThisCustomer.IsOver13 = ctrlBillingAddress.Over13Checked;
            }

            preferredShippingAddress.Name = ctrlShippingAddress.AccountName;
            preferredShippingAddress.EMail = ctrlBillingAddress.Email;
            preferredShippingAddress.ResidenceType = ctrlShippingAddress.ResidenceType;
            preferredShippingAddress.Address1 = ctrlShippingAddress.Address;
            preferredShippingAddress.City = ctrlShippingAddress.City;
            preferredShippingAddress.State = ctrlShippingAddress.State;
            preferredShippingAddress.PostalCode = ctrlShippingAddress.PostalCode;
            preferredShippingAddress.County = ctrlShippingAddress.County;
            preferredShippingAddress.Country = ctrlShippingAddress.CountryCode;
            preferredShippingAddress.Phone = ctrlShippingAddress.PhoneNumber;

            if (_weShouldRequirePayment)
            {
                if (ctrlPaymentTerm.PaymentTermCode.ToString().Equals("PURCHASE ORDER", StringComparison.InvariantCultureIgnoreCase))
                {
                    ThisCustomer.ThisCustomerSession.SetVal("PONumber", ctrlPaymentTerm.PONumber);
                }
                else if (ctrlPaymentTerm.PaymentTermCode.ToString().Equals("REQUEST QUOTE", StringComparison.InvariantCultureIgnoreCase))
                {
                }
                else if (ctrlPaymentTerm.PaymentMethod == PaymentTermControl.PAYMENT_METHOD_PAYPALX)
                {
                    ThisCustomer.ThisCustomerSession["paypalfrom"] = "onepagecheckout";
                    Response.Redirect(PayPalExpress.CheckoutURL(_cart));
                }
                else if (ctrlPaymentTerm.PaymentMethod == PaymentTermControl.PAYMENT_METHOD_CREDITCARD)
                {
                    if (!ctrlPaymentTerm.CardNumber.StartsWith("*"))
                    {
                        preferredBillingAddress.CardNumber = ctrlPaymentTerm.CardNumber;
                        preferredBillingAddress.CardName = ctrlPaymentTerm.NameOnCard;
                        preferredBillingAddress.CardType = ctrlPaymentTerm.CardType;
                        preferredBillingAddress.CardExpirationMonth = ctrlPaymentTerm.CardExpiryMonth;
                        preferredBillingAddress.CardExpirationYear = ctrlPaymentTerm.CardExpiryYear;

                        //Capture the credit card number from the payment page and encrypt it so that the gateway can capture from that credit card
                        string salt = null;
                        string iv = null;
                        string cardNumberEnc = AppLogic.EncryptCardNumber(preferredBillingAddress.CardNumber, ref salt, ref iv);
                        AppLogic.StoreCardNumberInSession(ThisCustomer, cardNumberEnc, salt, iv);

                        if (AppLogic.AppConfigBool("ShowCardStartDateFields"))
                        {
                            //Some CCs do not have StartDate, so here we should provide Default if none was supplied.
                            string defaultCardStartMonth = DateTime.Now.Month.ToString();
                            string defaultCardStartYear = DateTime.Now.Year.ToString();

                            preferredBillingAddress.CardStartMonth = CommonLogic.IIF(ctrlPaymentTerm.CardStartMonth != "MONTH", ctrlPaymentTerm.CardStartMonth, defaultCardStartMonth);
                            preferredBillingAddress.CardStartYear = CommonLogic.IIF(ctrlPaymentTerm.CardStartYear != "YEAR", ctrlPaymentTerm.CardStartYear, defaultCardStartYear);

                            preferredBillingAddress.CardIssueNumber = ctrlPaymentTerm.CardIssueNumber;
                        }
                    }

                    AppLogic.StoreCardExtraCodeInSession(ThisCustomer, ctrlPaymentTerm.CVV);
                }
            }
            this.hidBillCtrl.Value = string.Concat(ctrlBillingAddress.FindControl("WithStateCity").ClientID.ToString(), "*", ctrlBillingAddress.FindControl("WithStatePostalCode").ClientID.ToString(), "*ctrlBillingAddress_WithStateState", "*", ctrlBillingAddress.FindControl("WithoutStateCity").ClientID.ToString(), "*", ctrlBillingAddress.FindControl("WithoutStatePostalCode").ClientID.ToString());
            this.hidShipCtrl.Value = string.Concat(ctrlShippingAddress.FindControl("WithStateCity").ClientID.ToString(), "*", ctrlShippingAddress.FindControl("WithStatePostalCode").ClientID.ToString(), "*ctrlShippingAddress_WithStateState", "*", ctrlShippingAddress.FindControl("WithoutStateCity").ClientID.ToString(), "*", ctrlShippingAddress.FindControl("WithoutStatePostalCode").ClientID.ToString());

            var billCountry = CountryAddressDTO.Find(preferredBillingAddress.Country);
            var shipCountry = CountryAddressDTO.Find(preferredShippingAddress.Country);

            this.hidBlnWithState.Value = billCountry.withState.ToString();
            this.hidShpWithState.Value = shipCountry.withState.ToString();

            hidCheck.Value = chkSameAsBilling.Checked.ToString();

            //Checked to see Billing Address Info is the same with Shipping Address Info
            if (!this.chkSameAsBilling.Checked)
            {
                this.hidBillCheck.Value = CommonLogic.CheckIfAddressIsCorrect(preferredBillingAddress, billCountry);
                this.hidShipCheck.Value = CommonLogic.CheckIfAddressIsCorrect(preferredShippingAddress, shipCountry);
            }
            else
            {
                this.hidBillCheck.Value = CommonLogic.CheckIfAddressIsCorrect(preferredBillingAddress, billCountry);
                this.hidShipCheck.Value = string.Empty;

                preferredShippingAddress.Country = preferredBillingAddress.Country;
                preferredShippingAddress.State = preferredBillingAddress.State;
            }

            // Checked if either Billing Address or Shipping Address is Correct
            if (!string.IsNullOrEmpty(this.hidBillCheck.Value) || !string.IsNullOrEmpty(this.hidShipCheck.Value))
            {
                // Set the PopUp window to Show Up
                hidValid.Value = "false";

                hidSkinID.Value = ThisCustomer.SkinID.ToString();
                hidLocale.Value = ThisCustomer.LocaleSetting.ToString();

                // Collections of Caption/Labels/Headers, having ':' as its separator which be parsed at the receving end.
                this.hidBillTitle.Value = string.Concat(AppLogic.GetString("createaccount.aspx.87", ThisCustomer.SkinID, ThisCustomer.LocaleSetting));
                this.hidShipTitle.Value = string.Concat(AppLogic.GetString("createaccount.aspx.88", ThisCustomer.SkinID, ThisCustomer.LocaleSetting));

                this.hidBlnState.Value = preferredBillingAddress.State;
                this.hidBlnPostalCode.Value = preferredBillingAddress.PostalCode;
                this.hidBlnCountry.Value = preferredBillingAddress.Country;
                this.hidBlnCity.Value = preferredBillingAddress.City;

                this.hidShpState.Value = preferredShippingAddress.State;
                this.hidShpPostalCode.Value = preferredShippingAddress.PostalCode;
                this.hidShpCountry.Value = preferredShippingAddress.Country;
                this.hidShpCity.Value = preferredShippingAddress.City;

            }
            else
            {
                if (ThisCustomer.IsRegistered)
                {
                    Address.Update(ThisCustomer, preferredBillingAddress);
                    Address.Update(ThisCustomer, preferredShippingAddress);
                    UpdateShippingOnCart(preferredShippingAddress.AddressID);
                    preferredBillingAddress.MakeDefault();
                    preferredShippingAddress.MakeDefault();
                }
                else
                {
                    if (AppLogic.AppConfigBool("PasswordIsOptionalDuringCheckout") == true)
                    {
                        // for the address information
                        preferredBillingAddress.Save();

                        preferredShippingAddress.Save();

                        UpdateAnonCustomerRecordIsOver13();

                        preferredBillingAddress.Reload();
                        preferredShippingAddress.Reload();

                        ThisCustomer.PrimaryBillingAddress = preferredBillingAddress;
                        ThisCustomer.PrimaryShippingAddress = preferredShippingAddress;
                    }
                    else
                    {
                        try
                        {
                            // we assume that all the required fields are already pre-written
                            if (string.IsNullOrEmpty(preferredShippingAddress.Company))
                            {
                                preferredShippingAddress.Company = preferredBillingAddress.Company;
                            }
                            ThisCustomer.Register(preferredBillingAddress, preferredShippingAddress, true);
                        }
                        catch (Customer.CustomerRegistrationException regEx)
                        {
                            DisplayErrorMessageIfAny(regEx.Message);
                            return;
                        }

                        try
                        {
                            // send email notification...
                            AppLogic.SendMail(AppLogic.GetString("createaccount.aspx.27", ThisCustomer.SkinID, ThisCustomer.LocaleSetting),
                                AppLogic.RunXmlPackage(AppLogic.AppConfig("XmlPackage.WelcomeEmail"), null, ThisCustomer, this.SkinID, string.Empty, AppLogic.MakeXmlPackageParamsFromString("fullname=" + ThisCustomer.Name), false, false),
                                true,
                                AppLogic.AppConfig("MailMe_FromAddress"),
                                AppLogic.AppConfig("MailMe_FromName"),
                                ThisCustomer.EMail,
                                CommonLogic.IIF(ThisCustomer.IsRegistered, ThisCustomer.FirstName, ctrlBillingAddress.AccountName),
                                "",
                                AppLogic.AppConfig("MailMe_Server"));
                        }
                        catch { }

                        // at this point, the customer info has already been reloaded..
                        preferredBillingAddress.AddressID = ThisCustomer.PrimaryBillingAddressID;
                        preferredBillingAddress.CustomerCode = ThisCustomer.CustomerCode;

                        preferredShippingAddress.AddressID = ThisCustomer.PrimaryShippingAddressID;
                        preferredShippingAddress.CustomerCode = ThisCustomer.CustomerCode;

                        // update cc no# if specified...
                        Address.Update(ThisCustomer, preferredBillingAddress);
                        Address.Update(ThisCustomer, preferredShippingAddress);

                        // re-initialize the shoppoincart, this time data should be associated with the newly registered customer
                        InitializeShoppingCart();
                    }
                }

                if (_weShouldRequirePayment)
                {
                    InterpriseHelper.UpdateCustomerPaymentTerm(ThisCustomer, ctrlPaymentTerm.PaymentTermCode);
                }

                if (AppLogic.AppConfigBool("SkipShippingOnCheckout") ||
                    !_cart.HasShippableComponents())
                {
                    _cart.MakeShippingNotRequired();
                }
                else
                {
                    if (!_cartHasCouponAndIncludesFreeShipping)
                    {
                        _cart.SetCartShippingMethod(ctrlShippingMethod.ShippingMethodCode);
                    }
                    else
                    {
                        _cart.MakeShippingNotRequired();
                    }
                }

                if (AppLogic.AppConfigBool("Checkout.UseOnePageCheckout.UseFinalReviewOrderPage"))
                {
                    Response.Redirect("checkoutreview.aspx");
                }

                //// Else, Process Order here..
                string salesOrderCode = string.Empty;
                string receiptCode = string.Empty;
                Gateway gatewayToUse = null;

                string status = _cart.PlaceOrder(gatewayToUse, preferredBillingAddress, preferredShippingAddress, ref salesOrderCode, ref receiptCode, true, true, false);

                if (status == AppLogic.ro_3DSecure)
                { // If credit card is enrolled in a 3D Secure service (Verified by Visa, etc.)
                    Response.Redirect("secureform.aspx");
                }
                if (status == AppLogic.ro_OK)
                {
                    ThisCustomer.ClearTransactions(true);
                    Response.Redirect(string.Format("orderconfirmation.aspx?ordernumber={0}", Server.UrlEncode(salesOrderCode)));
                }
                else
                {
                    ThisCustomer.IncrementFailedTransactionCount();
                    if (ThisCustomer.FailedTransactionCount >= AppLogic.AppConfigUSInt("MaxFailedTransactionCount"))
                    {
                        _cart.ClearTransaction();
                        ThisCustomer.ResetFailedTransactionCount();
                        Response.Redirect("orderfailed.aspx");
                    }

                    ThisCustomer.ClearTransactions(false);

                    DisplayErrorMessageIfAny(status);
                }
            }
        }

        /// <summary>
        /// Update shippingaddressid field in shopping cart table to reflect changes.
        /// </summary>
        private void UpdateShippingOnCart(string addressID)
        {
            _cart.CartItems.ForEach(iseCartItem =>
            {
                string updateShoppingCartCommand = string.Format("update EcommerceShoppingCart set ShippingAddressID = {0} where ShoppingCartRecID={1} and CustomerCode={2}",
                DB.SQuote(addressID),
                iseCartItem.m_ShoppingCartRecordID,
                DB.SQuote(ThisCustomer.CustomerCode)
                );
                DB.ExecuteSQL(updateShoppingCartCommand);

            });
        }

        protected override void OnUnload(EventArgs e)
        {
            if (_cart != null)
            {
                _cart.Dispose();
            }
            base.OnUnload(e);
        }
    }
}